from threading import Thread, Lock
import time
from multiprocessing import Process, Lock, Queue

#第一问
#多进程锁
def one(num, lock):
    with lock:
        for i in range(num):
            print(f" {i}")



if __name__ == "__main__":
    p_array = []
    lock = Lock()
    for i in range(8):
        p_one = Process(target=one, args=(i, lock))
        p_array. append(p_one)
        p_one.start()
    for p_one in p_array:
        p_one. join()
    print("结束！")


#多线程锁
a = 0
lock = Lock()
def two():
    global a
    for i in range(10**3):
        with lock:
            a += 1
            a -= 1



if __name__ == "__main__":
    p_array = []
    lock = Lock()
    for i in range(8):
        t_two = Thread(target=two)
        p_array. append(t_two)
        t_two.start()
    for t_two in p_array:
        t_two. join()
    print(a)

#第二问，把进程通过Queue来实现进程通信
def three(num, my_queue):
    my_queue. put(num)

if __name__ == "__main__":
    p_array = []
    my_queue = Queue()
    for i in range(8):
        p_three = Process(target=three, args=(i, my_queue))
        p_array. append(p_three)
        p_three.start()
    for p_three in p_array:
        p_three. join()
    print("结束！")

    b = 0
    while b < 8:
        print(my_queue.get())
        b += 1




